/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import {store} from "@mall/api-services";
import * as _ from "lodash";
import * as React from "react";
import Flex from "../components/flex";
import Icon from "../icon";
import "./index.scss";

interface StoreCustomCollectionsProps {
    storeId: string;
}

interface StoreCustomCollectionsState {
    collections: store.CustomCollection[];
}

export class StoreCustomCollections extends React.Component<StoreCustomCollectionsProps, StoreCustomCollectionsState> {
    public constructor(props: Readonly<StoreCustomCollectionsProps>) {
        super(props);
        this.state = {
            collections: []
        };

        this.refreshCollections = this.refreshCollections.bind(this);
    }

    public componentDidMount(): void {
        this.refreshCollections();
    }

    public render() {
        const {collections} = this.state;
        return (
            <div className="storefront-custom-collections">
                {_.map(collections, this.renderTopCollection)}
            </div>
        );
    }

    private renderTopCollection = ({id, name, children}) => {

        return (
            <section key={id} className="storefront-custom-collection">
                <Flex className="custom-collection-name" justifyContent="space-between">
                    <span>{name}</span>
                    <Icon type="right" size="xs"/>
                </Flex>
                {!_.isEmpty(children) &&
                <div className="custom-collection-children">
                    {_.map(children, child => <span key={child.id}>{child.name}</span>)}
                </div>}
            </section>
        );
    };

    private refreshCollections() {
        const {storeId} = this.props;
        store.CustomCollectionServiceV1
            .getCollections(storeId)
            .then(collections => this.setState({collections}));

    }
}
